import request from '@/utils/request'
import { removeToken, setToken } from '@/utils/storage'

import { SET_TOKEN, DEL_TOKEN, DEL_USERINFO } from '../actionTypes'
export const useLogin = ({ mobile, code }) => {
  console.log('useLogin action', mobile, code)

  return async (dispatch) => {
    // 1. ajax
    const res = await request({
      url: '/authorizations',
      method: 'POST',
      data: { mobile, code }
    })
    // console.log(res.data.token)

    // 2. 保存结果到redux
    dispatch({ type: SET_TOKEN, payload: res.data.token })
    // 3. token持久化
    setToken(res.data.token)
  }
}

export const logout = () => {
  return (dispatch) => {
    // 1. 清空token
    removeToken()
    // 2. 清空redux
    dispatch({ type: DEL_TOKEN })
    dispatch({ type: DEL_USERINFO })
  }
}
